package cn.jhc.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jhc.bean.CartItem;
import cn.jhc.bean.UserCookie;
import cn.jhc.bean.User;

/**
 * Servlet implementation class DeleteBookServlet
 */
@WebServlet("/user/deletebook.do")
public class DeleteBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteBookServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String[] isbn = request.getParameterValues("check");
		if(isbn != null)
		{
			for (String id : isbn) 
			{
//				System.out.println(id);
				deleteBook(request, response, id);
			}
		}
		response.sendRedirect("./showcart.do");		
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String isbn = request.getParameter("isbn");
		if(isbn != null && !(isbn.equals("")))
		{
			deleteBook(request, response, isbn);			
		}
		response.sendRedirect("./showcart.do");
	}
	
	private void deleteBook(HttpServletRequest request, HttpServletResponse response, String isbn) 
			throws ServletException, IOException 
	{
		User user = (User)request.getSession().getAttribute("currentUser");
		String username = user.getLoginname();
		Cookie[] cookies = request.getCookies();
		Cookie c = UserCookie.tranversal(cookies, username);
		
		//存在cookie
		if(c != null)
		{
			List<CartItem> cart = new ArrayList<>();
			cart = UserCookie.getCartItems(c);
			
			String value = "";
			for (CartItem cartItem : cart) 
			{
				
				// 判断是否为该书
				if (isbn.equals(cartItem.getIsbn()))
				{
//					System.out.println("yes");
					value += "";//清除该书记录
				}
				else 
				{
//					System.out.println("no");
					value += "*" + cartItem.getIsbn() + "^"+ cartItem.getNum();
				}
			}
			

//			System.out.println("value" + value);
			c.setValue(value);
			
			//设置cookie的有效时间为一小时			
			c.setMaxAge(60 * 60);
			response.addCookie(c);
		}
	}

}
